#!/usr/bin/ruby
require 'rubygems'
require 'net/http'
require 'date'
require 'time'
require 'mysql'

unless (ARGV.length == 1) then
  puts "Usage: test.rb <start_date>" 
  Process.exit
end

d1 = Date.parse(ARGV[0])
d2 = Date.today

my = Mysql::new("localhost", "root", "ondu11a", "stockmarket_development")

exchanges = ["Nasdaq", "NYSE"]

exchanges.each do |exchange|

  res = my.query("select * from symbols where exchange = \"#{exchange}\"")
  res.each do |result|

    symbol = result[0].to_s
    puts "Processing Symbol #{symbol}..."

    uri = URI("http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=#{d1.month}&b=#{d1.day}&c=#{d1.year}&d=#{d2.month}&e=#{d2.day}&f=#{d2.year}&g=d&ignore=.csv")
    begin
      data = Net::HTTP.get_response(uri)
    rescue
      puts "Unknown error encountered for symbol #{symbol} !"
      next
    end
    if (!data.is_a?(Net::HTTPSuccess)) then
      puts "HTTP error for symbol #{symbol} !"
      next
    end

    data.body.each_line do |line|

      line = line.strip
      subs = line.split(",")
      if (subs[0].match("Date")) then
        next
      end

      t = Time.parse("4:00pm")

      my.query("REPLACE INTO `quotes` (`name`, `dividend_pay_date`, `pe_ratio`, `percent_change`, `price_over_book`, `days_range_hi`, `symbol`, `two_hundred_day_average`, `yr_range_hi`, `ask`, `price_over_sales`, `stock_exchange`, `todays_open`, `avg_daily_volume`, `days_range_lo`, `dividend_per_share`, `last_price`, `yr_range_lo`, `book_value`, `ebitda`, `eps_est_next_year`, `market_cap`, `volume`, `bid`, `eps_est_this_year`, `fifty_day_average`, `eps`, `last_trade_time`, `needs_adjust`, `peg_ratio`, `price_change`, `dividend_yield`, `eps_est_next_quarter`, `last_trade_date`, `previous_close`, `price_over_eps_next_year`, `price_over_eps_this_year`, `target_price`, `short_ratio`) VALUES(NULL, NULL, NULL, NULL, NULL, #{subs[2]}, '#{symbol}', NULL, NULL, NULL, NULL, NULL, #{subs[1].to_f}, NULL, #{subs[3].to_f}, NULL, #{subs[6].to_f}, NULL, NULL, NULL, NULL, NULL, #{subs[5].to_f}, NULL, NULL, NULL, NULL, '#{t.strftime("%H:%M:%S")}', 0, NULL, NULL, NULL, NULL, '#{subs[0]}', NULL, NULL, NULL, NULL, NULL)")


    end

  end

end





